package com.fhao.friend.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fhao.common.core.constants.Constants;
import com.fhao.common.core.domain.TableDataInfo;
import com.fhao.friend.domain.question.Question;
import com.fhao.friend.domain.question.dto.QuestionQueryDTO;
import com.fhao.friend.domain.question.es.QuestionES;
import com.fhao.friend.domain.question.vo.QuestionDetailVO;
import com.fhao.friend.domain.question.vo.QuestionVO;
import com.fhao.friend.elasticsearch.QuestionRepository;
import com.fhao.friend.manager.QuestionCacheManager;
import com.fhao.friend.mapper.question.QuestionMapper;
import com.fhao.friend.mapper.user.UserSubmitMapper;
import com.fhao.friend.service.question.IQuestionService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionCacheManager questionCacheManager;

    @Autowired
    private UserSubmitMapper userSubmitMapper;

    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        long count = questionRepository.count(); // 拿到索引中对应数据的数量
        if(count <= 0) {
            //刷新ES缓存.
            refreshQuestion();
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Integer difficulty = questionQueryDTO.getDifficulty();
        String keyword = questionQueryDTO.getKeyword();
        //第一页: 从0开始所以要减1
        Pageable pageable = PageRequest.of(questionQueryDTO.getPageNum()-1,questionQueryDTO.getPageSize(),sort);
        Page<QuestionES> questionESPage;
        if(difficulty == null && StrUtil.isEmpty(keyword)) {
            // 默认查询所有数据
            questionESPage = questionRepository.findAll(pageable);
        }else if (StrUtil.isEmpty(keyword)) {
            questionESPage = questionRepository.findQuestionByDifficulty(difficulty,pageable);
        }else if (difficulty == null) {
            questionESPage = questionRepository.findByTitleOrContent(keyword, keyword, pageable);
        }else {
            questionESPage = questionRepository.findByTitleOrContentAndDifficulty(keyword, keyword,difficulty,  pageable);
        }
        long total = questionESPage.getTotalElements();
        if (total <= 0) {
            return TableDataInfo.empty();
        }
        List<QuestionES> questionESList = questionESPage.getContent();
        //由于questionESList包含的信息太多,所以重新创建一个questionVOList类,专门用来返回给前端.
        List<QuestionVO> questionVOList = BeanUtil.copyToList(questionESList, QuestionVO.class);
        return TableDataInfo.success(questionVOList,total);
    }

    @Override
    public QuestionDetailVO detail(Long questionId) {
        //先去ES当中去查询, 如果没有就去数据库中查询并刷新缓存.
        QuestionES questionES = questionRepository.findById(questionId).orElse(null); //查得到就返回相应数据,查不到就返回null.
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        if(questionES != null) {
            //ES中有数据就返回
            BeanUtil.copyProperties(questionES,questionDetailVO);
            return questionDetailVO;
        }
        //ES中找不到数据,就去数据库中查,查到就刷新ES缓存
        Question question = questionMapper.selectById(questionId);
        if(question == null) {
            return null;
        }
        //刷新ES缓存
        refreshQuestion();
        BeanUtil.copyProperties(question,questionDetailVO);
        return questionDetailVO;
    }

    @Override
    public String preQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if(listSize == null || listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        //走到这里说明redis缓存当中一定有数据
        return questionCacheManager.preQuestion(questionId).toString();
    }

    @Override
    public String nextQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if(listSize == null || listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        //走到这里说明redis缓存当中一定有数据
        return questionCacheManager.nextQuestion(questionId).toString();
    }

    @Override
    public List<QuestionVO> hotList() {
        Long total = questionCacheManager.getHostListSize();
        List<Long> hotQuestionIdList;
        if (total == null || total <= 0) {
            PageHelper.startPage(Constants.HOST_QUESTION_LIST_START, Constants.HOST_QUESTION_LIST_END);
            hotQuestionIdList = userSubmitMapper.selectHostQuestionList();
            questionCacheManager.refreshHotQuestionList(hotQuestionIdList);
        } else {
            hotQuestionIdList = questionCacheManager.getHostList();
        }
        return assembleQuestionVOList(hotQuestionIdList);
    }

    private List<QuestionVO> assembleQuestionVOList(List<Long> hotQuestionIdList) {
        if (CollectionUtil.isEmpty(hotQuestionIdList)) {
            return new ArrayList<>();
        }
        List<QuestionVO> resultList = new ArrayList<>();
        for (Long questionId : hotQuestionIdList) {
            QuestionVO questionVO = new QuestionVO();
            QuestionDetailVO detail = detail(questionId);
            questionVO.setTitle(detail.getTitle());
            resultList.add(questionVO);
        }
        return resultList;
    }

    //刷新缓存.
    private void refreshQuestion() {
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<>());
        if(CollectionUtil.isEmpty(questionList)) {
            return;
        }
        //将questionList 数据类型转成  List<QuestionES>
        List<QuestionES> questionESList = BeanUtil.copyToList(questionList, QuestionES.class);
        questionRepository.saveAll(questionESList);//将数据库中的数据同步到 ES 当中.
    }
}


















